<template>
  <div class="login-container">
    <div class="viewbutton">
      <el-button
        class="gatherBtn"
        type="primary"
        size="mini"
        @click="save_cookie()"
        >保存当前页面Cookie</el-button
      >
      <el-button
        class="gatherBtn"
        type="primary"
        size="mini"
        @click="import_cookie()"
        >导入Cookie</el-button
      >
    </div>

    <div class="embedBox">
      <webview
        v-if="state.webviewShow"
        ref="gaungDongRef"
        class="contain"
        :src="state.url"
        partition="gaungDongStorePartition"
        allowpopups
      />
    </div>

    <el-dialog
      v-model="savecookirVisible"
      title="确定已是登录状态, 是否继续"
      width="500"
    >
      <el-form :model="savecookieform">
        <el-form-item label="选择账号" :label-width="formLabelWidth">
          <el-select
            v-model="savecookieform.account"
            filterable
            placeholder="选择账号"
            style="width: 240px"
          >
            <el-option
              v-for="item in accountselect"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="savecookirVisible = false">取消</el-button>
          <el-button type="primary" @click="submitsaveCookie"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import { saveAllAccountlist } from "@/api/account/index.ts";
import { savecookie } from "@/api/lutiancookie/index.ts";

import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute } from "@/api/main.js";

const activeuser = ref<any>({});

const gaungDongRef = ref();
const state = reactive({
  url: "https://member.ruten.com.tw/user/login.htm",
  cookiesArr: [],
  webviewShow: true,
  startCommodityLoad: false,
  webPreload: "",
});

const accountselect = ref([]);
const savecookirVisible = ref(false);
const savecookieStatus = ref(0);
const savecookieform = ref({
  account: "",
});

const save_cookie = () => {
  accountselect.value = [];
  // 保存Cookie
  if (activeuser.value.isadmin == 1 || activeuser.value.isadmin == 2) {
    let data = {
      keyword: "",
    };
    saveAllAccountlist(data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        res.data.forEach((item) => {
          let a = {
            value: item.id,
            label: item.account,
          };
          accountselect.value.push(a);
        });
      }
    });
  } else {
    if (activeuser.value.accounts != null && activeuser.value.accounts != "") {
      let accountsarr = activeuser.value.accounts.split(",");
      let accountsnamearr = activeuser.value.accountsname.split(",");

      for (let i = 0; i < accountsarr.length; i++) {
        let a = {
          value: accountsarr[i],
          label: accountsnamearr[i],
        };
        accountselect.value.push(a);
      }
    }
  }

  savecookirVisible.value = true;
  savecookieform.value.account = "";
  savecookieStatus.value = 0;
};

const import_cookie = () => {
  accountselect.value = [];
  // 保存Cookie
  if (activeuser.value.isadmin == 1 || activeuser.value.isadmin == 2) {
    let data = {
      keyword: "",
    };
    saveAllAccountlist(data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        res.data.forEach((item) => {
          let a = {
            value: item.id,
            label: item.account,
          };
          accountselect.value.push(a);
        });
      }
    });
  } else {
    if (activeuser.value.accounts != null && activeuser.value.accounts != "") {
      let accountsarr = activeuser.value.accounts.split(",");
      let accountsnamearr = activeuser.value.accountsname.split(",");

      for (let i = 0; i < accountsarr.length; i++) {
        let a = {
          value: accountsarr[i],
          label: accountsnamearr[i],
        };
        accountselect.value.push(a);
      }
    }
  }

  savecookirVisible.value = true;
  savecookieform.value.account = "";
  savecookieStatus.value = 1;
  // ipc.invoke(ipcApiRoute.importCookie).then((res) => {
  //   console.log(res);
  // });
};

const submitsaveCookie = () => {
  // console.log(activeuser.value);
  // console.log(savecookieform.value);
  if (savecookieform.value.account == "") {
    ElMessage({
      message: "请选择账号之后再保存cookie",
      type: "warning",
    });
  } else {
    if (savecookieStatus.value == 0) {
      ipc
        .invoke(
          ipcApiRoute.setCookie,
          JSON.stringify({
            webviewPartition: "gaungDongStorePartition",
            url: state.url,
          })
        )
        .then((res) => {
          console.log(res);
          let cookiestr = "";
          let filteredArray = accountselect.value.filter(
            (obj) => obj.value === savecookieform.value.account
          );

          res.forEach((item, index) => {
            let a = "";
            if (index + 1 == res.length) {
              a = `${item.name}=${item.value}`;
            } else {
              a = `${item.name}=${item.value};`;
            }
            cookiestr += a;
          });

          let match = cookiestr.match(/bid_rid=(\d+)/);
          if (match) {
            // 第一个捕获组（即(\d+)）中的内容就是连续的数字
            let numbers = match[1];
            ipc
              .invoke(ipcApiRoute.verificationcookie, {
                cookie: cookiestr,
                userid: numbers,
              })
              .then((res) => {
                if (res != "") {
                  console.log("有效");
                  let data = {
                    accountid: savecookieform.value.account,
                    accountname: filteredArray[0].label,
                    userId: activeuser.value.userId,
                    cookie: cookiestr,
                  };
                  savecookie(data).then((res2) => {
                    if (res2.code == 200) {
                      ElMessage({
                        message: res2.msg,
                        type: "success",
                      });

                      savecookirVisible.value = false;
                      savecookieform.value.account = "";
                    }
                  });
                } else {
                  ElMessage({
                    message: "当前cookie无效",
                    type: "warning",
                  });
                }
              });
          } else {
            ElMessage({
              message: "当前cookie无效",
              type: "warning",
            });
          }

          // console.log(data);
        });
    } else {
      ipc.invoke(ipcApiRoute.importCookie).then((res) => {
        console.log(res);
        
        console.log(JSON.parse(res));
        let jsonres = JSON.parse(res);
        let cookiestr = "";
        let filteredArray = accountselect.value.filter(
          (obj) => obj.value === savecookieform.value.account
        );
        jsonres.forEach((item, index) => {
          let a = "";
          if (index + 1 == jsonres.length) {
            a = `${item.name}=${item.value}`;
          } else {
            a = `${item.name}=${item.value};`;
          }
          cookiestr += a;
        });

        let match = cookiestr.match(/bid_rid=(\d+)/);
        if (match) {
          // 第一个捕获组（即(\d+)）中的内容就是连续的数字
          let numbers = match[1];
          ipc
            .invoke(ipcApiRoute.verificationcookie, {
              cookie: cookiestr,
              userid: numbers,
            })
            .then((res) => {
              if (res != "") {
                console.log("有效");
                let data = {
                  accountid: savecookieform.value.account,
                  accountname: filteredArray[0].label,
                  userId: activeuser.value.userId,
                  cookie: cookiestr,
                };
                savecookie(data).then((res2) => {
                  if (res2.code == 200) {
                    ElMessage({
                      message: res2.msg,
                      type: "success",
                    });

                    savecookirVisible.value = false;
                    savecookieform.value.account = "";
                  }
                });
              } else {
                ElMessage({
                  message: "当前cookie无效",
                  type: "warning",
                });
              }
            });
        } else {
          ElMessage({
            message: "当前cookie无效",
            type: "warning",
          });
        }
      });
    }
  }
};

onMounted(() => {
  activeuser.value = JSON.parse(localStorage.getItem("currentUserstr"));

  ipc
    .invoke(
      ipcApiRoute.deleteCookie,
      JSON.stringify({
        webviewPartition: "gaungDongStorePartition",
        url: state.url,
      })
    )
    .then((res) => {
      console.log(res);
    });
});
</script>

<style scoped>
.login-container {
  height: 100%;
}
.gatherBtn {
  display: flex;
  margin-bottom: 10px;
}
.embedBox {
  width: 100%;
  height: 90%;
}
.contain {
  width: 100%;
  height: 100%;
}

.viewbutton {
  display: flex;
}
</style>